<?php

namespace teach\controllers;

use backend\models\MallProduct;
use backend\models\MallProductSpecs;
use teach\components\WeChat;
use teach\components\WeChatRefund;
use teach\service\Business;
use teach\service\SendWechatMessage;
use teach\util\helper\ResponseHelper;
use Yii;
use yii\filters\VerbFilter;
use yii\web\Controller;

class ShopController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    '*' => ['post'],
                ],
            ],
        ];
    }

    /**
     * 商家信息
     * @return \yii\web\Response
     */
    public function actionInfo()
    {
        $request = Yii::$app->request;
        $mid = $request->post('mid');

        $msg = '';
        $flag = false;
        if (empty(isset($mid))) {
            $msg = 'mid 商家id不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shops = new Business();
            $map = " uid = {$mid}";
            $shop = $shops->shopInfo($map);

            if ($shop) {
                $mapper = " state = 1 ";
                $discount = $shops->shopDiscount($mapper);
                $rule = $shops->shopRule($mid);
                $shop['discount_name'] = $discount['name'];
                $shop['discount_value'] = $discount['value'];
                $shop['rule'] = $rule;
                $jsonData = ResponseHelper::buildJsonData(200, '成功', $shop);
            } else {
                $jsonData = ResponseHelper::buildJsonData(400, '商家不存在');
            }

        }

        return $this->asJson($jsonData);
    }

    /**
     * 商品中心
     */
    public function actionCenter()
    {
        $request = Yii::$app->request;
        $mid = $request->post('mid');

        $msg = '';
        $flag = false;

        if (!$mid) {
            $msg = 'mid 商家id不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shops = new Business();

            //查找出售中的商品 - 上架
            $map = " is_up = 1 AND status = 1 AND mid = {$mid} ";
            $up = $shops->shopSale($map);

            //查找仓库中的商品 - 下架
            $mapper = " is_up = -1 AND status = 1 AND mid = {$mid} ";
            $down = $shops->shopSale($mapper);

            //库存紧张的商品 库存小于 10
            $param = " 10 AND mid = {$mid}";
            $stock = $shops->shopStock($param);

            $shop['is_up'] = $up;
            $shop['is_down'] = $down;
            $shop['low_stock'] = $stock;

            $jsonData = ResponseHelper::buildJsonData(200, '成功', $shop);
        }

        return $this->asJson($jsonData);

    }

    /**
     * 商品中心下列表
     * @return \yii\web\Response
     */
    public function actionSale()
    {
        $request = Yii::$app->request;
        $mid = $request->post('mid');
        $state = $request->post('state');

        $msg = '';
        $flag = false;
        if (empty(isset($mid))) {
            $msg = 'mid 商家id不能为空';
        } elseif (!$state) {
            $msg = 'state 状态不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $page = $request->post('page');
            $page = $page ? $page : 1;

            $title = $request->post('title');

            $products = new Business();
            $productList = [];
            //state = 1 出售中的商品
            if ($state == 1) {
                $map = " is_up = 1 AND status = 1 AND mid = {$mid} ";
                if ($title) {
                    $map .= " AND title LIKE '%{$title}%' ";
                }
                $productList = $products->shopList($map, $page, $pre_page = 10);
            }

            //state = 2 仓库中的商品
            if ($state == 2) {
                $map = " is_up = -1 AND status = 1 AND mid = {$mid} ";
                if ($title) {
                    $map .= " AND title LIKE '%{$title}%' ";
                }
                $productList = $products->shopList($map, $page, $pre_page = 10);
            }

            //state = 3 库存紧张的商品
            if ($state == 3) {
                $map = " 10 AND p.mid = {$mid} ";
                if ($title) {
                    $map .= " AND title LIKE '%{$title}%' ";
                }
                $productList = $products->shopStockLow($map, $page, $pre_page = 10);
            }
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $productList);
        }

        return $this->asJson($jsonData);
    }

    /**
     * 发布商品
     * @return \yii\web\Response
     */
    public function actionRelease()
    {
        $request = Yii::$app->request;
        $mid = $request->post('mid');//商家id
        $cid = $request->post('cid');//商品分类
        $title = $request->post('title');//商品标题
        $img = $request->post('img'); //封面图
        $imgs = $request->post('imgs'); //商品展示
        $old_price = $request->post('old_price'); //原价
        $freight = $request->post('freight');//物流费
        $is_up = $request->post('is_up');//上否上架 -1下架 1上架
        $label = $request->post('label');
        $sku = $request->post('sku'); //商品sku属性

        if (!$label) {
            $label = -1;
        }

        //过滤关键词
        if($title) {
            $weChat = new WeChat();
            $ret = $weChat->textShan($title);
            if ($ret["data"]) {
                $data = json_decode($ret["data"], true);
                if ($data["Response"]["EvilTokens"] != []) {
                    if ($data["Response"]["EvilTokens"][0]["EvilFlag"] != 0) {
                        $jsonData = ResponseHelper::buildJsonData(400, "标题违规");
                        return $this->asJson($jsonData);
                    }
                }
            }
        }

        //查找用户是否已经加入了仓库
        $parent_id = $request->post('parent_id'); //父类产品
        $detail = $request->post('detail'); //底部详情图
        $detail_text = $request->post('detail_text');
        $video_url = $request->post('video_url');

        $msg = '';
        $flag = false;
        if (empty(isset($mid))) {
            $msg = 'mid 商家id不能为空';
        } elseif (!$cid) {
            $msg = 'cid 商品分类不能为空';
        } elseif (!$title) {
            $msg = 'title 商品标题不能为空';
        } elseif (!$img) {
            $msg = 'img 封面图不能为空';
        } elseif (!$imgs) {
            $msg = 'imgs 展示图不能为空';
        } elseif (!$old_price) {
            $msg = 'old_price 不能为空';
        } elseif (empty(isset($parent_id))) {
            $msg = 'parent_id 不能为空';
        } elseif (empty(isset($freight))) {
            $msg = 'freight 不能为空';
        } elseif (!$is_up) {
            $msg = 'is_up 不能为空';
        } elseif (!$label) {
            $msg = 'label 不能为空';
        } elseif (!$sku) {
            $msg = 'sku 属性不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shops = new Business();
            //从数据库中查找计算产生
            $param = " state = 1 ";
            $distribution = $shops->amountSplit($param);

            //查找折扣
//            $discount = $shops->shopDiscount($param);

            $level_one = $old_price * $distribution['level_one'];
            $level_two = $old_price * $distribution['level_two'];


            if ($parent_id) {
                //$mapper = " status = 1 AND parent_id  = {$parent_id} AND mid = {$mid} ";
                //$productCount = $shops->productCount($mapper);
                //if ($productCount >= 1) {
                $product = MallProduct::find()->where(['status' => 1, 'parent_id' => $parent_id, 'mid' => $mid])->one();
                if ($product) {
                    //产品已经存在说明需要更新
                    $product->scenario = 'update';
                    $product->aid = -1;
                    $product->cid = $cid;
                    $product->title = $title;
                    $product->img = $img;
                    $product->imgs = $imgs;
                    $product->detail = $detail;
                    $product->detail_text = $detail_text;
                    $product->is_up = $is_up;
                    $product->old_price = $old_price;
                    $product->freight = $freight;
                    $product->video_url = $video_url;
                    $product->label = strval($label);
                    $product->level_one = $level_one;
                    $product->level_two = $level_two;
                    $product->update_time = time();
                    if ($product->save()) {
                        //MallProductSpecs::deleteAll(['pid' => $product->id]);
                        MallProductSpecs::updateAll(['status' => -1],['pid'=> $product->id]);
                        $parameter = json_decode($sku, true);
                        $map = [];
                        foreach ($parameter as $item) {
                            $map[] = [
                                'pid' => $product->id,
                                'value' => $item['value'],
                                'stock' => $item['stock'],
                                'price' => $item['price'],
                                'img' => $item['img'],
                                'create_time' => time()
                            ];
                        }
                        $res = $shops->skuBatch($map);
                        if ($res) {
                            $jsonData = ResponseHelper::buildJsonData(200, '商品更新成功');
                        } else {
                            $jsonData = ResponseHelper::buildJsonData(400, '商品更新失败,请再次更新');
                        }

                    } else {
                        $jsonData = ResponseHelper::buildJsonData(400, '商品更新失败,请再次更新');
                    }
                    return $this->asJson($jsonData);
                }
            }


            $no = "NO." . $shops->createNoncestr(20);

            //查找折扣价跟赚钱的比例

            $model = new MallProduct();
            $model->scenario = 'create';
            $model->aid = -1;//是否admin
            $model->mid = $mid;
            $model->cid = $cid;
            $model->title = $title;
            $model->img = $img;
            $model->imgs = $imgs;
            $model->detail = $detail;
            $model->parent_id = $parent_id;
            $model->detail_text = $detail_text;
            $model->is_up = $is_up;
            $model->old_price = $old_price;
            $model->freight = $freight;
            $model->video_url = $video_url;
            $model->label = strval($label);
            $model->no = $no;
            $model->level_one = $level_one;
            $model->level_two = $level_two;
            $model->update_time = time();
            $model->create_time = time();
            $model->sort = 1000;
            $model->count_sale = 0;
            $model->up_time = time();
            $model->status = 1;

            if ($model->save()) {
                $parameter = json_decode($sku, true);
                $map = [];
                foreach ($parameter as $item) {
                    $map[] = [
                        'pid' => $model->id,
                        'value' => $item['value'],
                        'stock' => $item['stock'],
                        'price' => $item['price'],
                        'img' => $item['img'],
                        'create_time' => time()
                    ];
                }
                $res = $shops->skuBatch($map);
                if ($res) {
                    $jsonData = ResponseHelper::buildJsonData(200, '添加成功', $model->id);
                } else {
                    $jsonData = ResponseHelper::buildJsonData(400, '商品属性添加失败');
                }

            } else {
                $jsonData = ResponseHelper::buildJsonData(400, '商品添加失败');
            }

        }
        return $this->asJson($jsonData);

    }

    /**
     * 编辑商品
     * @return \yii\web\Response
     */
    public function actionEdit()
    {
        $request = Yii::$app->request;

        //如果parent_id = 0 编辑自己上传的商品 ！=0 编辑系统上传的商品
        $parent_id = $request->post('parent_id');

        $msg = '';
        $flag = false;

        if (empty(isset($parent_id))) {
            $msg = 'parent_id 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            //
            $flag = false;
            if ($parent_id == 0) {
                //编辑自己的产品
                $pid = $request->post('pid');
                $mid = $request->post('mid');
                $cid = $request->post('cid');
                $title = $request->post('title');
                $img = $request->post('img');
                $imgs = $request->post('imgs');
                $detail = $request->post('detail');
                $detail_text = $request->post('detail_text');
                $old_price = $request->post('old_price');
                $freight = $request->post('freight');
                $is_up = $request->post('is_up');
                $label = $request->post('label');
                $sku = $request->post('sku');

                //过滤关键词
                if($title) {
                    $weChat = new WeChat();
                    $ret = $weChat->textShan($title);
                    if ($ret["data"]) {
                        $data = json_decode($ret["data"], true);
                        if ($data["Response"]["EvilTokens"] != []) {
                            if ($data["Response"]["EvilTokens"][0]["EvilFlag"] != 0) {
                                $jsonData = ResponseHelper::buildJsonData(400, "标题违规");
                                return $this->asJson($jsonData);
                            }
                        }
                    }
                }

                if (!$pid) {
                    $msg = 'pid 商品id 不能为空';
                } elseif (!$mid) {
                    $msg = 'mid 商家id不能为空';
                } elseif (!$cid) {
                    $msg = 'cid 商品分类不能为空';
                } elseif (!$title) {
                    $msg = 'title 标题不能为空';
                } elseif (!$img) {
                    $msg = 'img 封面图不能为空';
                } elseif (!$imgs) {
                    $msg = 'imgs 展示图不能为空';
                } elseif (!$old_price) {
                    $msg = 'old_price 原价不能为空';
                } elseif (!$freight) {
                    $msg = 'freight 邮费不能为空';
                } elseif (!$is_up) {
                    $msg = 'is_up 是否上架不能为空';
                } elseif (!$label) {
                    $msg = 'label 不能为空';
                } elseif (!$sku) {
                    $msg = 'sku 不能为空';
                } else {
                    $flag = true;
                }

                if (!$flag) {
                    $jsonData = ResponseHelper::buildJsonData(400, $msg);
                } else {
                    $shops = new Business();
                    //从数据库中查找计算产生
                    $param = " state = 1 ";
                    $distribution = $shops->amountSplit($param);

                    //查找折扣
//                    $discount = $shops->shopDiscount($param);
                    $level_one = $old_price * $distribution['level_one'];
                    $level_two = $old_price * $distribution['level_two'];

                    $model = MallProduct::find()->where(['id' => $pid, 'mid' => $mid])->one();
                    if (null == $model) {
                        $jsonData = ResponseHelper::buildJsonData(400, '产品信息不存在');
                        return $this->asJson($jsonData);
                    }

                    $model->scenario = 'update';
                    $model->cid = $cid;
                    $model->title = $title;
                    $model->img = $img;
                    $model->imgs = $imgs;
                    $model->detail = $detail;
                    $model->detail_text = $detail_text;
                    $model->old_price = $old_price;
                    $model->freight = $freight;
                    $model->is_up = $is_up;
                    $model->level_one = $level_one;
                    $model->level_two = $level_two;
                    $model->up_time = time();
                    $model->update_time = time();
                    $model->label = $label;
                    if ($model->save()) {
                        $parameter = json_decode($sku, true);

                       // MallProductSpecs::deleteAll(['pid' => $pid]);
                        MallProductSpecs::updateAll(['status' => -1],['pid'=> $pid]);

                        foreach ($parameter as $item) {
                            //说明是新的 插入
                            $productSku = new MallProductSpecs;
                            $productSku->pid = $pid;
                            $productSku->value = $item['value'];
                            $productSku->stock = $item['stock'];
                            $productSku->price = $item['price'];
                            $productSku->img = $item['img'];
                            $productSku->create_time = time();
                            $productSku->save();
                        }

                        $jsonData = ResponseHelper::buildJsonData(200, '产品修改成功', $pid);

                    } else {
                        $jsonData = ResponseHelper::buildJsonData(400, '产品修改失败');
                    }

                }

                return $this->asJson($jsonData);


            } else {
                //编辑商品中心的商品
                $pid = $request->post('pid');
                $mid = $request->post('mid');
                $img = $request->post('img');//封面图
                $title = $request->post('title');//标题
                $sku = $request->post('sku');//sku属性
                $freight = $request->post('freight');//运费
                $is_up = $request->post('is_up');//上架 or 放入仓库
                $old_price = $request->post('old_price');//旧的价格


                //过滤关键词
                if($title) {
                    $weChat = new WeChat();
                    $ret = $weChat->textShan($title);
                    if ($ret["data"]) {
                        $data = json_decode($ret["data"], true);
                        if ($data["Response"]["EvilTokens"] != []) {
                            if ($data["Response"]["EvilTokens"][0]["EvilFlag"] != 0) {
                                $jsonData = ResponseHelper::buildJsonData(400, "标题违规");
                                return $this->asJson($jsonData);
                            }
                        }
                    }
                }

                if (!$pid) {
                    $msg = 'pid 商品id不能空';
                } elseif (!$mid) {
                    $msg = 'mid 商家id不能为空';
                } elseif (!$img) {
                    $msg = 'img 封面图不能为空';
                } elseif (!$title) {
                    $msg = 'title 标题不能为空';
                } elseif (!$sku) {
                    $msg = 'sku 属性不能为空';
                } elseif (!$freight) {
                    $msg = 'freight 运费不能为空';
                } elseif (!$is_up) {
                    $msg = 'is_up 是否上架不能为空';
                } elseif (!$old_price) {
                    $msg = 'old_price 不能为空';
                } else {
                    $flag = true;
                }

                if (!$flag) {
                    $jsonData = ResponseHelper::buildJsonData(400, $msg);
                } else {
                    $shops = new Business();
                    //从数据库中查找计算产生
                    $param = " state = 1 ";
                    $distribution = $shops->amountSplit($param);
                    //查找折扣
//                    $discount = $shops->shopDiscount($param);
                    $level_one = $old_price * $distribution['level_one'];
                    $level_two = $old_price * $distribution['level_two'];

                    $model = MallProduct::find()->where(['id' => $pid])->one();
                    if (null == $model) {
                        $jsonData = ResponseHelper::buildJsonData(400, '产品信息不存在');
                        return $this->asJson($jsonData);
                    }

                    //判断用户编辑的产品是否已经存在
                    $productExist = MallProduct::find()->where(['mid' => $mid, 'parent_id' => $parent_id, 'status' => 1])->one();
                    if (null == $productExist) {
                        $modelNew = new MallProduct();
                        $modelNew->scenario = 'create';
                        $modelNew->aid = -1;
                        $modelNew->mid = $mid;
                        $modelNew->cid = $model->cid;
                        $modelNew->video_url = $model->video_url;
                        $modelNew->title = $title;
                        $modelNew->img = $img;
                        $modelNew->imgs = $model->imgs;
                        $modelNew->detail = $model->detail;
                        $modelNew->detail_text = $model->detail_text;
                        $modelNew->old_price = $old_price;
                        $modelNew->freight = $freight;
                        $modelNew->sort = 1000;
                        $modelNew->count_sale = 0;
                        $modelNew->is_up = $is_up;
                        $modelNew->up_time = time();
                        $modelNew->update_time = time();
                        $modelNew->create_time = time();
                        $modelNew->status = 1;
                        $modelNew->parent_id = $parent_id;
                        $modelNew->label = $model->label;
                        $modelNew->no = "NO." . $shops->createNoncestr(20);
                        $modelNew->level_one = $level_one;
                        $modelNew->level_two = $level_two;

                        if ($modelNew->save()) {
                            $parameter = json_decode($sku, true);

                            //MallProductSpecs::deleteAll(['pid' => $modelNew->id]);
                            MallProductSpecs::updateAll(['status' => -1],['pid'=> $modelNew->id]);
                            foreach ($parameter as $item) {
                                $skuOne = new MallProductSpecs();
                                $skuOne->pid = $modelNew->id;
                                $skuOne->value = $item['value'];
                                $skuOne->stock = $item['stock'];
                                $skuOne->price = $item['price'];
                                $skuOne->img = $item['img'];
                                $skuOne->create_time = time();
                                $skuOne->save();
                            }
                            $jsonData = ResponseHelper::buildJsonData(200, '产品修改成功', $pid);
                        } else {
                            $jsonData = ResponseHelper::buildJsonData(400, '产品修改失败', $pid);
                        }
                    } else {
                        $productExist->scenario = 'update';
                        $productExist->aid = -1;
                        $productExist->mid = $mid;
                        $productExist->cid = $model->cid;
                        $productExist->title = $title;
                        $productExist->img = $img;
                        $productExist->imgs = $model->imgs;
                        $productExist->detail = $model->detail;
                        $productExist->detail_text = $model->detail_text;
                        $productExist->old_price = $old_price;
                        $productExist->freight = $freight;
                        $productExist->sort = 1000;
                        $productExist->count_sale = 0;
                        $productExist->is_up = $is_up;
                        $productExist->up_time = time();
                        $productExist->update_time = time();
                        $productExist->create_time = time();
                        $productExist->status = 1;
                        $productExist->parent_id = $parent_id;
                        $productExist->label = $model->label;
                        $productExist->no = "NO." . $shops->createNoncestr(20);
                        $productExist->level_one = $level_one;
                        $productExist->level_two = $level_two;

                        if ($productExist->save()) {
                            $parameter = json_decode($sku, true);

                            //MallProductSpecs::deleteAll(['pid' => $productExist->id]);
                            MallProductSpecs::updateAll(['status' => -1],['pid'=> $productExist->id]);
                            foreach ($parameter as $item) {
                                $skuOne = new MallProductSpecs();
                                $skuOne->pid = $productExist->id;
                                $skuOne->value = $item['value'];
                                $skuOne->stock = $item['stock'];
                                $skuOne->price = $item['price'];
                                $skuOne->img = $item['img'];
                                $skuOne->create_time = time();
                                $skuOne->save();
                            }
                            $jsonData = ResponseHelper::buildJsonData(200, '产品修改成功', $pid);
                        } else {
                            $jsonData = ResponseHelper::buildJsonData(400, '产品修改失败', $pid);
                        }
                    }
                }

            }

            return $this->asJson($jsonData);
        }
        return $this->asJson($jsonData);

    }

    /**
     * 获取首页广告图
     * @return \yii\web\Response
     */
    public function actionAd()
    {
        $request = Yii::$app->request;
        $style = $request->post('style');

        $msg = '';
        $flag = false;
        if (!$style) {
            $msg = 'style 不能为空';
        } else {
            $flag = true;
        }


        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {

            $shop = new Business();
            $map = " status = 1 AND style = {$style}";
            $ad = $shop->shopAd($map);
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $ad);
        }

        return $this->asJson($jsonData);
    }

    /**
     * 设置店铺信息
     * @return \yii\web\Response
     */
    public function actionSet()
    {
        $request = Yii::$app->request;
        $uid = $request->post('mid');
        $name = $request->post('name');
        $avatar = $request->post('avatar');
        $ad = $request->post('ad');

        $discount = $request->post('discount');
        $low_total_fee = $request->post('low_total_fee');
        $logistic_fee = $request->post('logistic_fee');


        $msg = '';
        $flag = false;
        if (!$uid) {
            $msg = 'mid 不能为空';
        } elseif (!$name) {
            $msg = 'name 不能为空';
        } elseif (!$avatar) {
            $msg = 'avatar 不能为空';
        } elseif (!$ad) {
            $msg = 'ad 不能为空';
        } elseif (!$discount) {
            $msg = 'discount 不能为空';
        } elseif (!$low_total_fee) {
            $msg = 'low_total_fee 不能为空';
        } elseif (!$logistic_fee) {
            $msg = 'logistic_fee 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shops = new Business();
            $time = time();
            $map = " name = '{$name}', avatar = '{$avatar}' , update_time = {$time}, ad = '{$ad}' ";
            $where = " uid = {$uid} ";
            $andMap = " discount = {$discount}, low_total_fee = {$low_total_fee}, logistic_fee = {$logistic_fee} ";
            $andWhere = " mid = {$uid}";
            $res = $shops->shopSet($map, $where, $andMap, $andWhere);
            if ($res) {
                $jsonData = ResponseHelper::buildJsonData(200, '成功');
            } else {
                $jsonData = ResponseHelper::buildJsonData(400, '失败');
            }
        }

        return $this->asJson($jsonData);
    }

    /**
     * 修改 | 输入 快递公司名跟单号
     * @return \yii\web\Response
     */
    public function actionExpress()
    {
        $request = Yii::$app->request;
        $oid = $request->post('oid');
        $mid = $request->post('mid');
        $logistics = $request->post('logistics');
        $order_num = trim($request->post('order_num'));

        $msg = '';
        $flag = false;
        if (!$oid) {
            $msg = 'oid 订单号不能为空';
        } elseif (!$mid) {
            $msg = 'mid 商家id不能为空';
        } elseif (!$logistics) {
            $msg = 'logistics 不能为空';
        } elseif (!$order_num) {
            $msg = 'order_num 物流单号不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shops = new Business();
            $time = time();
            $where = " mid = {$mid} AND id = {$oid} ";
            $order = $shops->orderOne($where);

            //订单是否存在
            if (!$order) {
                $jsonData = ResponseHelper::buildJsonData(400, '订单有误');
                return $this->asJson($jsonData);
            }

            //订单是否是已支付状态
            if ($order['status'] != 1) {
                $jsonData = ResponseHelper::buildJsonData(400, '请勿非法操作');
                return $this->asJson($jsonData);
            }
            $map = " logistics = '{$logistics}', order_num = '{$order_num}', status = 2, send_time = {$time} ";

            $res = $shops->orderExpress($map, $where);
            if ($res) {
                $this->Send($order, $logistics, $order_num);
                $jsonData = ResponseHelper::buildJsonData(200, '成功');
            } else {
                $jsonData = ResponseHelper::buildJsonData(400, '失败');
            }
        }
        return $this->asJson($jsonData);
    }

    private function Send($order, $logistics, $order_num)
    {
        //$redis = Yii::$app->redis;
        $SendWeChatMessage = new SendWechatMessage();
        //告诉用户已经发货
        $tip = "商品已经发货,具体物流信息请在小程序中查看";

        $WeChat = new WeChat();
        //小程序模板消息
//        while (true) {
//            $formid = $redis->rpop("formid_{$order['openid']}");
//            $status = $WeChat->sendMsg($SendWeChatMessage->deliver($order['openid'], $formid, $order['out_trade_no'], $order['phone'], $order['name'], $logistics, $order_num, $tip));
//            if ($status['errcode'] == 0 || $formid == false) {
//                break;
//            }
//        }

        //小程序订阅消息
        $WeChat->send($SendWeChatMessage->delivers($order["openid"], $order["out_trade_no"], $logistics, $order_num));



        //查找商家,发送小程序消息
        $shop = new Business();
        $andWhere = " id = {$order['mid']} ";
        $store = $shop->storeOne($andWhere);
//        while (true) {
//            $formid_store = $redis->rpop("formid_{$store['openid']}");
//            $status_store = $WeChat->sendMsg($SendWeChatMessage->deliver($store['openid'], $formid_store, $order['out_trade_no'], $order['phone'], $order['name'], $logistics, $order_num, $tip));
//            if ($status_store['errcode'] == 0 || $formid_store == false) {
//                break;
//            }
//        }
        //小程序订阅消息
        $WeChat->send($SendWeChatMessage->delivers($store["openid"], $order["out_trade_no"], $logistics, $order_num));

    }

    public function actionTest()
    {
        $sql = "SELECT * FROM mall_order WHERE id = 17";
        $order = Yii::$app->db->createCommand($sql)->queryOne();
        $this->Send($order, '京东', '111111111');
    }

    /**
     * 查看店铺中的分销商
     * @return \yii\web\Response
     */
    public function actionTeam()
    {
        $request = Yii::$app->request;
        $mid = $request->post('mid');

        $msg = '';
        $flag = false;
        if (!$mid) {
            $msg = 'mid 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $page = $request->post('page');
            $page = $page ? $page : 1;
            $name = $request->post('name');
            $uid = $request->post('uid');
            $where = " mall_id = {$mid} AND mall_is = 0 ";
            if ($uid) {
                $where .= " AND mall_superior = {$uid} ";
            }
            if ($name) {
                $where .= " AND (phone = '{$name}' OR mall_rname = '{$name}' OR nickname LIKE '%{$name}%') ";
            }
            $filter = " mid = {$mid}";
            $teams = new Business();
            $distribution = $teams->distribution($filter);
            $teamList = $teams->storeTeam($distribution,$where, $page, $pre_page = 10);
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $teamList);
        }
        return $this->asJson($jsonData);
    }

    /**
     * 产品 上架 下架 删除处理
     * @return \yii\web\Response
     */
    public function actionDeal()
    {
        $request = Yii::$app->request;
        $products = $request->post('products');
        $mid = $request->post('mid');
        $state = $request->post('state'); //1上架 2是下架 3删除

        $msg = '';
        $flag = false;
        if (!$products) {
            $msg = 'products 产品集不能为空';
        } elseif (!$mid) {
            $msg = 'mid 商家id不能为空';
        } elseif (!$state) {
            $msg = 'state 状态不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shops = new Business();
            $pds = json_decode($products, true);
            foreach ($pds as $key => $val) {
                //看看每个产品的需要的key存在不存在
                if (!array_key_exists('pid', $val)) {
                    $jsonData = ResponseHelper::buildJsonData(400, '缺少产品key值:pid');
                    return $this->asJson($jsonData);
                }
            }

            if ($state == 1) {
                foreach ($pds as $k_key => $k_val) {
                    $where = " id = {$k_val['pid']} AND mid = {$mid} ";
                    $shops->productUp($where);
                }
                $jsonData = ResponseHelper::buildJsonData(200, '成功');
                return $this->asJson($jsonData);
            }

            if ($state == 2) {
                foreach ($pds as $p_key => $p_val) {
                    $where = " id = {$p_val['pid']} AND mid = {$mid} ";
                    $shops->productDown($where);
                }
                $jsonData = ResponseHelper::buildJsonData(200, '成功');
                return $this->asJson($jsonData);
            }

            //批量删除
            if ($state == 3) {
                foreach ($pds as $_key => $_val) {
                    $where = " id = {$_val['pid']} AND mid = {$mid} ";
                    $shops->productDelete($where);
                }
                $jsonData = ResponseHelper::buildJsonData(200, '成功');
                return $this->asJson($jsonData);
            }

            $jsonData = ResponseHelper::buildJsonData(400, '非法操作');
        }

        return $this->asJson($jsonData);
    }

    /**
     * 商城提现规则 引导用户去公众号提现
     * @return \yii\web\Response
     */
    public function actionMoneyruler()
    {
        $where = " state = 1 ";
        $shop = new Business();
        $rule = $shop->moneyRuler($where);
        if ($rule) {
            $jsonData = ResponseHelper::buildJsonData(200, '成功', $rule);
        } else {
            $jsonData = ResponseHelper::buildJsonData(400, '失败');
        }
        return $this->asJson($jsonData);
    }

    public function actionStar()
    {
        $request = Yii::$app->request;
        $uid = $request->post('uid');
        $mid = $request->post('mid');
        $star = $request->post('star');

        $msg = '';
        $flag = false;
        if (!$uid) {
            $msg = 'uid 不能为空';
        } elseif (!$mid) {
            $msg = 'mid 不能为空';
        } elseif (!$star) {
            $msg = 'star 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shops = new Business();
            //判断用户是否存在或者合法的
            $whereFilter = " id = {$uid} AND mall_id = {$mid} ";
            $user = $shops->userOne($whereFilter);
            if (!$user) {
                $jsonData = ResponseHelper::buildJsonData(400, '用户信息有误');
                return $this->asJson($jsonData);
            }

            //商家是否存在
            $andWhereFilter = " id = {$mid} AND mall_is = 1 ";
            $shop = $shops->userOne($andWhereFilter);
            if (!$shop) {
                $jsonData = ResponseHelper::buildJsonData(400, '商家信息有误');
                return $this->asJson($jsonData);
            }

            $arr = [3, 5, 6, 7];
            if (!in_array($star, $arr)) {
                $jsonData = ResponseHelper::buildJsonData(400, '星级选择有误');
                return $this->asJson($jsonData);
            }
            //查询规则分数
            $filter = " mid = {$mid}";
            $distribution = $shops->distribution($filter);
            switch ($star) {
                case 3:
                    $score_total = $distribution['three_star_score'];
                    break;
                case 5:
                    $score_total = $distribution['five_star_score'];
                    break;
                case 6:
                    $score_total = $distribution['six_star_score'];
                    break;
                case 7:
                    $score_total = $distribution['seven_star_score'];
                    break;
            }

            $map = " score_total = {$score_total} ";
            $where = " id = {$uid}";
            $record = [
                'uid' => $uid,
                'mid' => $mid,
                'star' => $star,
                'create_time' => time()
            ];
            $res = $shops->userStarChange($map, $where, $record);
            if ($res) {
                $jsonData = ResponseHelper::buildJsonData(200, '修改成功');
            } else {
                $jsonData = ResponseHelper::buildJsonData(400, '修改失败');
            }
        }
        return $this->asJson($jsonData);
    }

    public function actionRefund()
    {
        $request = Yii::$app->request;

        $oid = $request->post('oid');
        $mid = $request->post('mid');
        $uid = $request->post('uid');
        $is_refuse = $request->post('is_refuse');//1通过 -1 拒绝
        $amount = $request->post('amount');//退款的金额

        $msg = '';
        $flag = false;

        if (!$oid) {
            $msg = 'oid 不能为空';
        } elseif (!$mid) {
            $msg = 'mid 不能为空';
        } elseif (!$uid) {
            $msg = 'uid 不能为空';
        } elseif (!$amount) {
            $msg = 'amount 不能为空';
        } elseif (!$is_refuse) {
            $msg = 'is_refuse 不能为空';
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {

            $shop = new Business();
            $where = " orders.id = {$oid} AND orders.mid = {$mid} ";
            $order = $shop->orderRefundOne($where);
            if (!$order) {
                $jsonData = ResponseHelper::buildJsonData(400, '订单不存在');
                return $this->asJson($jsonData);
            }

            //订单抓过你太是否status = 2
            if ($order['order_status'] != -2) {
                $jsonData = ResponseHelper::buildJsonData(400, '订单状态错误');
                return $this->asJson($jsonData);
            }

            $SendWeChatMessage = new SendWechatMessage();
            $redis = Yii::$app->redis;
            $WeChat = new WeChat();

            //拒绝, 将订单改为-6
            if ($is_refuse == -1) {
                $map = " status = 2";
                $whereFilter = " id = {$oid} AND mid = {$mid} ";
                $res = $shop->orderRefundStatus($map, $whereFilter);
                $shop->orderPayStatus($order['p_id']);
                if ($res) {
                    //拒绝退款 发送小程序消息
                    while (true) {
                        $formid = $redis->rpop("formid_{$order['openid']}");
                        $status = $WeChat->sendMsg($SendWeChatMessage->refundStatus($order['openid'],$formid, $order['out_trade_no'], '拒绝退款',$order['total_fee'], '如有疑问请联系商家','请在订单管理查看详情'));
                        if ($status['errcode'] == 0 || $formid == false) {
                            break;
                        }
                    }
                    $jsonData = ResponseHelper::buildJsonData(200, '拒绝成功');
                } else {
                    $jsonData = ResponseHelper::buildJsonData(400, '拒绝失败,联系开发者');
                }
                return $this->asJson($jsonData);
            }

            //确认退款
            if ($is_refuse == 1) {
                //校对金额是否是订单以内的数额
                if ($amount > $order['total_fee']) {
                    $jsonData = ResponseHelper::buildJsonData(400, '退款金额大于收款金额');
                    return $this->asJson($jsonData);
                }

                //调起微信做退款操作 把微信操作返回信息用json存在pay中
                $appid = Yii::$app->params['serviceNum'][$mid]['appid']; //公众号appid
                $mch_id = Yii::$app->params['serviceNum']['mchId']; //服务商号
                $sub_mch_id = Yii::$app->params['serviceNum'][$mid]['sub_mch_id'];
                $key = Yii::$app->params['serviceNum']['md5Key']; //支付密匙设置
                $transaction_id = $order['transaction_id']; //微信订单号
                $out_refund_no = 'Refund' . date('Ymd') . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);; //退款订单号
                $total_fee = $order['total_fee']; //订单金额
                $refund_fee = (float)number_format($amount, 2, '.', ''); //申请退款金额
                $WeChatRefund = new WeChatRefund($appid, $mch_id, $key, $sub_mch_id, $transaction_id, $out_refund_no, $total_fee, $refund_fee);
                $result = $WeChatRefund->refund();
                if ($result['return_code'] == 'SUCCESS') {
                    if ($result['result_code'] == 'SUCCESS') {
                        //退款成功
                        $pay_id = $order['p_id'];
                        $out_trade_no = $order['out_trade_no'];
                        $res_json = json_encode($result, true);
                        $ret = $shop->orderBatchStatus($pay_id, $oid, $out_trade_no, $res_json);
                        if ($ret) {
                            //退款成功后 发送小程序消息
                            while (true) {
                                $formid = $redis->rpop("formid_{$order['openid']}");
                                $status = $WeChat->sendMsg($SendWeChatMessage->refundStatus($order['openid'],$formid, $order['out_trade_no'], '退款成功',$order['total_fee'], '如有疑问请联系商家','请在订单管理查看详情'));
                                if ($status['errcode'] == 0 || $formid == false) {
                                    break;
                                }
                            }
                            $jsonData = ResponseHelper::buildJsonData(200, '调用成功,退款成功,记录成功');
                            return $this->asJson($jsonData);
                        } else {
                            $jsonData = ResponseHelper::buildJsonData(200, '调用成功,退款成功,记录失败');
                            return $this->asJson($jsonData);
                        }
                    }
                } else {
                    $jsonData = ResponseHelper::buildJsonData(40, '调用失败,退款失败', $result);
                    return $this->asJson($jsonData);
                }
            }
            $jsonData = ResponseHelper::buildJsonData(400, '非法操作');
        }
        return $this->asJson($jsonData);
    }

    /**
     * 查找一条退款申请
     * @return \yii\web\Response
     */
    public function actionRefundDetail()
    {
        $request = Yii::$app->request;
        $oid = $request->post('oid');
        $uid = $request->post('uid');
        $mid = $request->post('mid');
        $out_trade_no = $request->post('out_trade_no');

        $msg = '';
        $flag = false;

        if (!$oid) {
            $msg = "oid 不能为空";
        } elseif (!$uid) {
            $msg = "uid 不能为空";
        } elseif (!$mid) {
            $msg = "mid 不能为空";
        } elseif (!$out_trade_no) {
            $msg = "out_trade_no 不能为空";
        } else {
            $flag = true;
        }

        if (!$flag) {
            $jsonData = ResponseHelper::buildJsonData(400, $msg);
        } else {
            $shop = new Business();
            $where = " oid = {$oid} AND uid = {$uid} AND mid = {$mid} AND out_trade_no = '{$out_trade_no}'";
            $refund = $shop->refundOne($where);
            if ($refund) {
                $enum[1] = "1我要退款（无需退货)";
                $enum[2] = "我要退货退款";
                $refund['types'] = $enum[$refund['types']];
                $jsonData = ResponseHelper::buildJsonData(200, '成功', $refund);
            } else {
                $jsonData = ResponseHelper::buildJsonData(400, '申请不存在');
            }
        }
        return $this->asJson($jsonData);
    }
}